﻿using System;
using System.Drawing;
using System.Drawing.Text;
using System.IO;

namespace CreateImage
{
    class Program
    {
        static void Main(string[] args)
        {
            var text = "早上睡的迷迷糊糊，老婆趴在我身上撒娇:老公，我想买个包包？我:买！“老公，我还想买套化妆品？”我:买买买！老婆高兴的走开了。。。没想到啊没想到，三岁的儿子趴在我身上:老公，我想买个奥特曼。早上睡的迷迷糊糊，老婆趴在我身上撒娇:老公，我想买个包包？我:买！“老公，我还想买套化妆品？”我:买买买！老婆高兴的走开了。。。没想到啊没想到，三岁的儿子趴在我身上:老公，我想买个奥特曼。早上睡的迷迷糊糊，老婆趴在我身上撒娇:老公，我想买个包包？我:买！“老公，我还想买套化妆品？”我:买买买！老婆高兴的走开了。。。没想到啊没想到，三岁的儿子趴在我身上:老公，我想买个奥特曼。早上睡的迷迷糊糊，老婆趴在我身上撒娇:老公，我想买个包包？我:买！“老公，我还想买套化妆品？”我:买买买！老婆高兴的走开了。。。没想到啊没想到，三岁的儿子趴在我身上:老公，我想买个奥特曼。";
            //AddTextToImg(text);
            var newFilePath = "D:/MyProject/CreateImage/CreateImage/images/bg1.jpg";
            AddStringToImg(newFilePath, text);

        }

        private static void AddStringToImg(string SavePath, string text, string strFontPath = null)
        {
            int phWidth = 480;

            var tarFile = "D:/MyProject/CreateImage/CreateImage/images/bg.jpg";
            //读取一个bmp图片
            Image newImage = new Bitmap(tarFile);
            //新建一个画板
            Graphics g = Graphics.FromImage(newImage);
            //设置质量
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //置背景色

            //画图
            g.DrawImage(newImage, 0, 0);

            #region 自定义字体
            //路径       
            strFontPath = strFontPath ?? @"D:\MyProject\createimage\CreateImage\simkai.ttf";
            //读取字体文件             
            PrivateFontCollection pfc = new PrivateFontCollection();
            pfc.AddFontFile(strFontPath);
            //实例化字体
            float fontSize = 22;
            Font font = new Font(pfc.Families[0], fontSize);
            #endregion

            // 自定义行间距
            SizeF fit = new SizeF(phWidth, font.Height);
            StringFormat fmt = StringFormat.GenericTypographic;
            int spacing = (int)(font.Height-10);
            //自定义字体颜色
            Brush brush = new SolidBrush(Color.FromArgb(65, 65, 65));
            int line = 7;
            if (text.Length > 174)
            {
                text = text.Substring(0, 174)+"...";
            }
            for (int ix = 0; ix < text.Length;)
            {
                int chars, lines;
                g.MeasureString(text.Substring(ix), font, fit, fmt, out chars, out lines);
                g.DrawString(text.Substring(ix, chars), font, brush, 10, spacing * line);
                ++line;
                ix += chars;
            }
            //保存图
            newImage.Save(SavePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            //释放资源
            g.Dispose();
            newImage.Dispose();
        }
    }
}
